using SimpleJSON;
using UnityEngine;

namespace Gj
{
    public class LoadingHelper : NodeHelper
    {
        public ProgressHelper Progress;
        public float refreshTime = 0.25f;
        public string timeKey = "time";
        public string directionKey = "direction";
        private int direction;
        private float endTime;
        private float startTime;
        private float totalTime;
        private float value;

        protected override BindDataType bindDataType => BindDataType.Object;

        protected override void BindData(JSONObject obj)
        {
            if (obj.IsNull || endTime == obj[timeKey].AsInt) return;
            endTime = obj[timeKey].AsInt;
            direction = obj[directionKey].AsInt;
            startTime = Time.time;
            totalTime = endTime - startTime;
            if (totalTime <= 0) Progress.gameObject.SetActive(false);
            switch (direction)
            {
                case 1:
                    value = 0;
                    break;
                case -1:
                    value = 100f;
                    break;
            }

            InvokeRepeating("UpdateLoading", 0, refreshTime);
            Progress.gameObject.SetActive(true);
        }


        private void UpdateLoading()
        {
            value = totalTime / 100 * (endTime - Time.time);
            if (value > 100) value = 100;
            if (value < 0) value = 0;
            Progress.SetData(value);
            if (value == 0 || value == 100) CancelInvoke("UpdateLoading");
        }
    }
}